package com.fastloan.mgt.home.controller;

import com.alibaba.fastjson.JSON;
import com.fastloan.mgt.home.model.HomeConfig;
import com.fastloan.mgt.home.service.HomeConfigService;
import com.fastloan.safe.core.util.ManagerKit;
import com.fastloan.safe.mgt.org.model.CmuOrg;
import com.fastloan.safe.mgt.org.service.CmuOrgService;
import com.fastloan.safe.mgt.sys.model.vo.AddressFiled;
import com.fastloan.safe.mgt.sys.service.CmChinaCityService;
import com.kawins.base.baseabs.BaseController;
import com.kawins.result.ResultEnum;
import com.kawins.result.ResultTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yanwe
 * createTime 2017-11-2017/11/16 15:06
 */
@RestController
@RequestMapping("/api/home")
public class HomeConfigController extends BaseController<HomeConfig> {

    @Autowired
    private HomeConfigService homeConfigService;

    @Autowired
    private CmChinaCityService cmChinaCityService;

    @Autowired
    private CmuOrgService orgService;

    @PostMapping("/{orgId}")
    public ResultTo add(@PathVariable("orgId") String orgId, @RequestParam("homeConfigJson") String homeConfigJson) {
        List<HomeConfig> homeConfigs = JSON.parseArray(homeConfigJson, HomeConfig.class);
        homeConfigs.forEach(homeConfig -> homeConfig.setOrgId(orgId));
        homeConfigService.addHomeConfig(homeConfigs);
        return new ResultTo();
    }

    @PostMapping("/file")
    public ResultTo uploadFile(@RequestPart("files") MultipartFile[] files) {
        return new ResultTo().setData(homeConfigService.uploadFile(files));
    }

    @GetMapping("/edit")
    public ResultTo getHomePage(@RequestParam(value = "orgId",required = false) String orgId) {
        return new ResultTo().setData(homeConfigService.getHomeConfig(orgId == null
                ? Collections.singletonList(ManagerKit.getOrgId()) : Collections.singletonList(orgId),null))
                .setData("orgId",ManagerKit.getOrgId());
    }

    @GetMapping("/anon/app")
    public ResultTo getHomePage(AddressFiled addressFiled) {
        AddressFiled address = cmChinaCityService.selectAllIdByAdd(addressFiled);
        Example example = new Example(CmuOrg.class);
        example.createCriteria().andIn("areaId"
                , Arrays.asList(address.getAreaId(),address.getCityId(),address.getProvinceId()));
        List<CmuOrg> org = orgService.selectByExample(example);
        if (org.isEmpty()){
            return new ResultTo(ResultEnum.OPERATION_FAILED,"该地区没有机构!");
        }
        return new ResultTo().setData(homeConfigService.getHomeConfig(org.stream()
                .map(CmuOrg::getId).collect(Collectors.toList())));
    }
}
